const Sequelize = require('sequelize');
const {getTimeZone} = require('./dateUtil');
// const {database, dbUser, dbPwd, host, port} = require('../conf/cfg').cfg.db.mysql.bigScreen;
const _cfg = require('../conf/cfg').cfg.db.mysql;

let msyqlins = {};
// //链接GM数据库
// const sequelize = new Sequelize(database, dbUser, dbPwd, {
//     host: host,
//     dialect: 'mysql',
//     port: port,
//     timezone: getTimeZone(),
//     pool: {
//         max: 5,
//         min: 0,
//         idle: 3000
//     },
//     timestamps: false,
//     paranoid: true,
//     // query: {raw: true},
//     logging: function (sql) {
//         console.log('sql :', sql);
//     }
// });
//
// sequelize.authenticate() //验证链接
//     .then(function () {
//         console.log('mysql已成功建立连接')
//     })
//     .catch(function (err) {
//         console.log('无法连接到mysql数据库:', JSON.stringify(err))
//     });

function getInstance(cfgname) {
    cfgname = cfgname || "default";

    if (msyqlins[cfgname]) {
        return msyqlins[cfgname];
    } else {
        let cfg = _cfg[cfgname];
        msyqlins[cfgname] = new Sequelize(cfg.database, cfg.dbUser, cfg.dbPwd, {
            host: cfg.host,
            dialect: 'mysql',
            port: cfg.port,
            timezone: getTimeZone(),
            pool: {
                max: 5,
                min: 0,
                idle: 3000
            },
            timestamps: false,
            paranoid: true,
            // query: {raw: true},
            logging: function (sql) {
                console.log('sql :', sql);
            }
        })
        msyqlins[cfgname].authenticate() //验证链接
            .then(function () {
                console.log('mysql已成功建立连接')
            })
            .catch(function (err) {
                console.log('无法连接到mysql数据库:', JSON.stringify(err))
            });
        return msyqlins[cfgname]
    }
}

module.exports = {getInstance};